import axios from 'axios'
import { ElMessage } from 'element-plus'
import { logout } from '@/common'
const instance = axios.create({
    baseURL: "/api"
})
instance.interceptors.request.use(function (config) {
    let token = localStorage.getItem("token");
    if (token) {
        if (config.headers) {
            config.headers["Authorization"] = token;
        }
    }
    return config;
}, function (error) {
    return Promise.reject(error);
});

instance.interceptors.response.use(function (response) {
    const data = response.data as IResponse<any>
    if (data.code === 401) {
        logout(undefined, () => {
            ElMessage.error("token过期，请重新登录");
        })
    } else if (data.code !== 200) {
        ElMessage.error(data.message);
    }
    return response.data;
}, function (error) {
    ElMessage.error("请求失败，错误信息:" + error.message);
    Promise.reject(error)
});
export default instance